package cn.e3mall.item.listener;

import cn.e3mall.item.pojo.Item;
import cn.e3mall.manager.service.ItemService;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbItemDesc;
import freemarker.core.ParseException;
import freemarker.template.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class HtmlListener implements MessageListener {

    private final Logger logger = LoggerFactory.getLogger(HtmlListener.class);

    @Autowired
    private ItemService itemService;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${freeMark.path}")
    private String freeMakerpath;
    @Override
    public void onMessage(Message message) {
        //          获取消息内容
        TextMessage textMessage = (TextMessage) message;
        String text = null;
        try {
            text = textMessage.getText();
            System.out.println("======================="+text);
            Thread.sleep(100);
            Long id =new Long(text);
            TbItem itemById = itemService.getItemById(id);
            Item item = new Item(itemById);
            TbItemDesc itemDesc = itemService.findDesc(id);
            Map map = new HashMap();
            map.put("item",item);
            map.put("itemDesc",itemDesc);
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            Template template = configuration.getTemplate("item.ftl");
            logger.info("开始生成静态页面");
            Writer out = new FileWriter(new File(freeMakerpath+id+".html"));
            //8、生成静态页面
            template.process(map, out);
            //9、关闭流
            out.close();
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (TemplateNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }

    }
}
